package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.FileHttpUtils
import cn.com.kh.KHDBConfig
import cn.com.kh.KHFileUtil
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONObject
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: 数字化城管对接3高转发
 *
 */

public class apiDataExchange implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiDataExchange.class);
    private static long startTime = System.currentTimeMillis();

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        startTime = System.currentTimeMillis();

        String callJson = "";
        JSONObject resultJ = new JSONObject();
        resultJ.put("code", 1);
        resultJ.put("msg", "处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));

        if (getMethod.equals("GET")) {
            callJson = request.getParameter("data");
            log.debug("原始Get请求参数:" + callJson);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                callJson += line;
            }
            log.debug("原始Post请求参数:" + callJson);
        }

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(callJson);
            log.debug("处理前的Json：" + inObject.toString());
            String timestamp = KHUtil.GetJV(inObject, "timestamp");//时间戳
            String sign = KHUtil.GetJV(inObject, "sign");//密钥
            log.debug("解析信息-" + " timestamp: " + timestamp + " sign: " + sign);

            String apiid = "waterOff";
            String apikey = "55bd38420d354822bdb789284fac4ab3";

            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + apikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);
            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!sign.equals(signafter)) {
                log.debug("signafter不存在");
                resultJ.put("code", -1);
                resultJ.put("msg", "处理失败(sign签名错误),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
            } else {
                // 识别调用类型
                if (inObject.has("newLimit")) {
                    resultJ = newLimit(eliteBean, inObject);

                } else if (inObject.has("evtIds")) {
                    JSONArray arr = evtIds(eliteBean, inObject);
                    resultJ.put("data", arr);
                    resultJ.put("msg", "处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));

                } else if (inObject.has("returnDescribe")) {
                    resultJ = returnDescribe(eliteBean, inObject);

                } else if (inObject.has("completeTime")) {
                    resultJ = completeTime(eliteBean, inObject);

                } else if (inObject.has("DateType")) {
                    String evtId = KHUtil.GetJV(inObject, "evtId");
                    if (!evtId.equals("")) {
                        JSONArray arr = GetData(eliteBean, evtId);
                        log.debug("获取工单数据arr" + arr);
                        resultJ.put("data", arr);
                        resultJ.put("msg", "处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                    } else {
                        resultJ.put("code", -2);
                        resultJ.put("msg", "处理失败(szh_workid参数错误),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                    }
                } else {
                    resultJ.put("code", -4);
                    resultJ.put("msg", "处理失败(未知类型),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                }

            }

        } catch (Exception e) {
            log.error("接口处理异常-" + e.getMessage());
            // 失败返回
            resultJ.put("code", -1);
            resultJ.put("msg", "接口处理异常" + e.getMessage() + ",调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "数字化城管对接3高转发", "apiDataExchange", callJson, resultJ.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        log.debug("数字化城管对接3高转发返回结果:" + resultJ.toString());

        return resultJ.toString();
    }

    // 申请延期
    private static JSONObject newLimit(EliteBean eliteBean, JSONObject inObject) {
        JSONObject resultJ = new JSONObject();
        resultJ.put("code", 1);
        resultJ.put("msg", "申请延期 完成");
        try {
            //取传参
            String evtId = KHUtil.GetJV(inObject, "evtId");//案件ID
            String newLimit = KHUtil.GetJV(inObject, "newLimit");//延期申请的时间
            String reqUserName = KHUtil.GetJV(inObject, "reqUserName");//申请人姓名
            String reqReason = KHUtil.GetJV(inObject, "reqReason");//申请理由
            String activityInstId = KHUtil.GetJV(inObject, "activityInstId");//环节实例 id
            String filestr = KHUtil.GetJV(inObject, "umEvtAttachList");//附件

            // 拼接获取各类调用必填参数信息
            String isCheckNull = KHUtil.isNullMSG("evtId", evtId) + KHUtil.isNullMSG("reqUserName", reqUserName) + KHUtil.isNullMSG("newLimit", newLimit) + KHUtil.isNullMSG("reqReason", reqReason);

            // 如果必填参数信息不为空说明有为空参数
            if (!KHUtil.isNull(isCheckNull)) {
                resultJ.put("code", -2);
                resultJ.put("msg", "调用参数非空校验异常:" + isCheckNull + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
            } else {
                //activityInstId校验保护
                if (KHUtil.isNull(activityInstId)) {
                    List activityInstlist = eliteBean.chaxun_sql("Select top 1 R1.Activityinstid From Szwg_De_Case_Tasks R1 Left Join (Select Evtid, Max(Sync_Time) Max_Sync_Time From Szwg_De_Case_Tasks With(Nolock) Where Evtid = '" + evtId + "' Group By Evtid) R2 On R1.Evtid = R2.Evtid And R1.Sync_Time = R2.Max_Sync_Time Where R2.Evtid Is Not Null  And R1.Evtid = '" + evtId + "'", "dataSource");
                    if (activityInstlist.size() == 0) {
                        resultJ.put("msg", "Activityinstid获取失败！");
                        resultJ.put("code", "-1");
                        return resultJ;
                    } else {
                        activityInstId = activityInstlist[0].getAt("Activityinstid");
                    }
                }

                boolean doResult = dealAttachList(eliteBean, evtId, filestr, "");
                log.debug("附件处理结果:" + doResult);

                //申请延期数据推送处理
                String[] data = new String[3];
                data[0] = "insert into SZWG_DE_Case_ReqDate ( rec_Id, evtId, newLimit, reqDate, reqUserName, reqUserDeptName, reqReason, activityInstId, params )VALUES(newid(), '" + evtId + "','" + newLimit + "',GETDATE(),'" + reqUserName + "','深圳市水务（集团）有限公司','" + reqReason + "','" + activityInstId + "',newid())";
                data[1] = "update SZWG_DE_Case_List set status_flag='YSSQ',operation_staffid='SELITE',operation_group='SYSTEM',operation_time=GETDATE()  where evtId='" + evtId + "'";
                data[2] = "Insert into SZWG_DE_Case_List_His select * from SZWG_DE_Case_List where evtId ='" + evtId + "'";
                int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                log.debug("申请延期SQL处理结果:" + dataresult.toString());
            }
        } catch (Exception e) {
            log.error("申请延期数据处理异常" + e.getMessage());
            // 失败返回
            resultJ.put("code", -1);
            resultJ.put("msg", "申请延期数据处理异常" + e.getMessage());
        }
        return resultJ;

    }

    // 申请回退
    private static JSONObject returnDescribe(EliteBean eliteBean, JSONObject inObject) {
        JSONObject resultJ = new JSONObject();
        resultJ.put("code", 1);
        resultJ.put("msg", "申请回退 完成");
        try {
            //取传参
            String evtId = KHUtil.GetJV(inObject, "evtId");//案件ID
            String reqUserName = KHUtil.GetJV(inObject, "reqUserName");//申请人姓名
            String returnDescribe = KHUtil.GetJV(inObject, "returnDescribe");//申请回退理由
            String activityInstId = KHUtil.GetJV(inObject, "activityInstId");//环节实例 id
            String filestr = KHUtil.GetJV(inObject, "umEvtAttachList");//附件

            // 拼接获取各类调用必填参数信息
            String isCheckNull = KHUtil.isNullMSG("evtId", evtId) + KHUtil.isNullMSG("reqUserName", reqUserName) + KHUtil.isNullMSG("returnDescribe", returnDescribe);

            // 如果必填参数信息不为空说明有为空参数
            if (!KHUtil.isNull(isCheckNull)) {
                resultJ.put("code", -2);
                resultJ.put("msg", "调用参数非空校验异常:" + isCheckNull + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
            } else {
                String reCaseStaus = checkCaseStaus(eliteBean, evtId, "申请回退");
                if (KHUtil.isNull(reCaseStaus)) {

                    //activityInstId校验保护
                    if (KHUtil.isNull(activityInstId)) {
                        List activityInstlist = eliteBean.chaxun_sql("Select top 1 R1.Activityinstid From Szwg_De_Case_Tasks R1 Left Join (Select Evtid, Max(Sync_Time) Max_Sync_Time From Szwg_De_Case_Tasks With(Nolock) Where Evtid = '" + evtId + "' Group By Evtid) R2 On R1.Evtid = R2.Evtid And R1.Sync_Time = R2.Max_Sync_Time Where R2.Evtid Is Not Null  And R1.Evtid = '" + evtId + "'", "dataSource");
                        if (activityInstlist.size() == 0) {
                            resultJ.put("msg", "环节实例 id Activityinstid获取失败！");
                            resultJ.put("code", -3);
                            return resultJ;
                        } else {
                            activityInstId = activityInstlist[0].getAt("Activityinstid");
                        }
                    }

                    //校验同activityInstId同evtId是否之前有进行过回退成功过
                    List ReqCompleteList = eliteBean.chaxun_sql("select rec_Id from SZWG_DE_Case_ReqReturn where activityInstId='" + activityInstId + "' and evtId='" + evtId + "' and errorMsg='交易成功'", "dataSource");
                    if (ReqCompleteList.size() > 0) {
                        resultJ.put("msg", "已向数值化城管回退成功,不允许再次提交！");
                        resultJ.put("code", "-1");
                    } else {

                        boolean doResult = dealAttachList(eliteBean, evtId, filestr, "");
                        log.debug("附件处理结果:" + doResult);

                        //申请回退数据处理
                        String[] data = new String[3];
                        data[0] = "insert into SZWG_DE_Case_ReqReturn(rec_Id,evtId,returnDescribe,reqDate,reqUserName,reqUserDeptName,activityInstId,fromId)VALUES(newid(),'" + evtId + "','" + returnDescribe + "',GETDATE(),'" + reqUserName + "','深圳市水务（集团）有限公司','" + activityInstId + "',newid())";
                        data[1] = "update SZWG_DE_Case_List set status_flag='HT',operation_staffid='SELITE',operation_group='SYSTEM',operation_time=GETDATE() where evtId='" + evtId + "'";
                        data[2] = "Insert into SZWG_DE_Case_List_His select * from SZWG_DE_Case_List where evtId ='" + evtId + "'";
                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("申请退回SQL处理结果:" + dataresult.toString());
                    }

                } else {
                    resultJ.put("msg", reCaseStaus);
                    resultJ.put("code", "-1");

                }
            }

        } catch (Exception e) {
            log.error("申请退回数据处理异常" + e.getMessage());

            // 失败返回
            resultJ.put("code", -1);
            resultJ.put("msg", "申请退回数据处理异常" + e.getMessage());
        }
        return resultJ;
    }

    // 反馈结果
    private static JSONObject completeTime(EliteBean eliteBean, JSONObject inObject) {
        JSONObject resultJ = new JSONObject();
        resultJ.put("code", 1);
        resultJ.put("msg", "反馈结果 完成");
        try {
            //取传参
            String evtId = KHUtil.GetJV(inObject, "evtId");//案件ID
            String handlerName = KHUtil.GetJV(inObject, "handlerName");//申请人姓名
            String remark = KHUtil.GetJV(inObject, "remark");//处理意见
            String taskId = KHUtil.GetJV(inObject, "taskId");//任务taskId_id
            String activityInstId = KHUtil.GetJV(inObject, "activityInstId");//环节实例 id
            String filestr = KHUtil.GetJV(inObject, "umEvtAttachList");//附件

            // 拼接获取各类调用必填参数信息
            String isCheckNull = KHUtil.isNullMSG("evtId", evtId) + KHUtil.isNullMSG("handlerName", handlerName) + KHUtil.isNullMSG("remark", remark);

            // 如果必填参数信息不为空说明有为空参数
            if (!KHUtil.isNull(isCheckNull)) {
                resultJ.put("code", -2);
                resultJ.put("msg", "调用参数非空校验异常:" + isCheckNull + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
            } else {
                String reCaseStaus = checkCaseStaus(eliteBean, evtId, "结果反馈");
                if (KHUtil.isNull(reCaseStaus)) {

                    //activityInstId校验保护
                    if (KHUtil.isNull(activityInstId)) {
                        List activityInstlist = eliteBean.chaxun_sql("Select top 1 R1.Activityinstid, r1.Id From Szwg_De_Case_Tasks R1 Left Join (Select Evtid, Max(Sync_Time) Max_Sync_Time From Szwg_De_Case_Tasks With(Nolock) Where Evtid = '" + evtId + "' Group By Evtid) R2 On R1.Evtid = R2.Evtid And R1.Sync_Time = R2.Max_Sync_Time Where R2.Evtid Is Not Null  And R1.Evtid = '" + evtId + "'", "dataSource");
                        if (activityInstlist.size() == 0) {
                            resultJ.put("msg", "Activityinstid获取失败！");
                            resultJ.put("code", "-1");
                            return resultJ;
                        } else {
                            activityInstId = activityInstlist[0].getAt("Activityinstid");
                            taskId = KHUtil.isNull(taskId) ? activityInstlist[0].getAt("Id") : taskId;
                        }
                    }
                    //校验同activityInstId同evtId是否之前有进行过反馈成功过
                    List ReqCompleteList = eliteBean.chaxun_sql("select rec_Id from SZWG_DE_Case_ReqComplete where  activityInstId='" + activityInstId + "' and evtId='" + evtId + "' and errorMsg='交易成功'", "dataSource");
                    if (ReqCompleteList.size() > 0) {
                        resultJ.put("msg", "已向数值化城管反馈成功,不允许再次提交！");
                        resultJ.put("code", "-1");
                    } else {
                        String Rec_ID = KHUtil.getRandomString(36).toUpperCase();

                        boolean doResult = dealAttachList(eliteBean, evtId, filestr, Rec_ID);
                        log.debug("附件处理结果:" + doResult);

                        //反馈结果数据处理
                        String[] data = new String[3];
                        data[0] = "INSERT INTO SZWG_DE_Case_ReqComplete(rec_Id,evtId,activityInstId,taskId,handlerId,handlerName,deptId,deptName,completeTime,remark)VALUES('" + Rec_ID + "','" + evtId + "','" + activityInstId + "','" + taskId + "','SELITE','" + handlerName + "','10116','深圳市水务（集团）有限公司',GETDATE(),'" + remark + "')";
                        data[1] = "update SZWG_DE_Case_List set status_flag='JGFK',operation_staffid='SELITE',operation_group='SYSTEM',operation_time=GETDATE(),deal_result='',fault_reason='" + remark + "',color_flag='4'  where evtId='" + evtId + "'";
                        data[2] = "Insert into SZWG_DE_Case_List_His select * from SZWG_DE_Case_List where evtId ='" + evtId + "'";

                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("反馈结果SQL处理结果:" + dataresult.toString());
                    }
                } else {
                    resultJ.put("msg", reCaseStaus);
                    resultJ.put("code", "-1");

                }
            }
        } catch (Exception e) {
            log.error("反馈结果数据处理异常" + e.getMessage());
            // 失败返回
            resultJ.put("code", -1);
            resultJ.put("msg", "反馈结果数据处理异常" + e.getMessage());
        }
        return resultJ;

    }

    // 申请延期结果查询
    private static JSONArray evtIds(EliteBean eliteBean, JSONObject inObject) {
        JSONArray rearr = new JSONArray();
        try {
            //取传参
            String evtIds = KHUtil.GetJV(inObject, "evtIds");//案件ID
            evtIds = evtIds.replaceAll("\\[", "\\(");
            evtIds = evtIds.replaceAll("\\]", "\\)");
            evtIds = evtIds.replace('\"', '\'');
            log.debug("evtIdsaaaa:" + evtIds);

            List ResultList = eliteBean.chaxun_sql("Select DISTINCT LTrim(RTrim(R2.evtId)) as evtId, R2.auditDate,R2.auditUserName,R2.auditType,R2.auditOpinion, R2.isPass,R2.oldLimit,R2.selfDefLimit,LTrim(RTrim(R2.params)) as params, Convert(Varchar(100),R2.createTime,20) as Createtime From Szwg_De_Case_Reqdate R1 Left Join Szwg_De_Case_Reqdate_Result R2 On R1.Evtid = R2.Evtid And R1.Params = R2.Params And R1.Createtime <= R2.Createtime Where R1.Evtid in " + evtIds + " Order By Createtime Desc", "dataSource");
            log.debug("evtIdsaaaa DB ResultList:" + ResultList);


            if (ResultList.size() > 0) {
                rearr = new JSONArray(Util.getJsonArrayFromList(ResultList).toString());
            }

        } catch (Exception e) {
            log.error("申请延期结果查询异常" + e.getMessage());
        }
        return rearr;

    }

    // 数据获取
    private static JSONArray GetData(EliteBean eliteBean, String evtId) {
        JSONArray rearr = new JSONArray(Util.getJsonArrayFromList(eliteBean.chaxun_sql("select * from SGGD_DB_CASE_GROOVY where evtId='" + evtId + "'", "dataSource")).toString());
        return rearr;

    }

    // 处理附件数据
    private static boolean dealAttachList(EliteBean eliteBean, String evtId, String AttachList, String Rec_Id) {
        boolean reResult = false;

        String H3_WoAttac_Before = KHDBConfig.getParamConfig(eliteBean, "3H_WoAttac_Before");
        String H3_WoAttac_After = KHDBConfig.getParamConfig(eliteBean, "3H_WoAttac_After");
        String H3_WoAttac_TempPath = KHDBConfig.getParamConfig(eliteBean, "3H_WoAttac_TempPath");
        String WoAttac_CGSYS = KHDBConfig.getParamConfig(eliteBean, "WoAttac_CGSYS");

        try {

            if (!KHUtil.isNull(AttachList)) {
                JSONArray filearr = new JSONArray(AttachList);
                for (int i = 0; i < filearr.length(); i++) {
                    //写入附件数据
                    String attachType = KHUtil.GetJV(filearr.getJSONObject(i), "attachType");
                    String attachFilePath = KHUtil.GetJV(filearr.getJSONObject(i), "attachFilePath");
                    String attachFileName = KHUtil.GetJV(filearr.getJSONObject(i), "attachFileName");

                    if (!KHUtil.isNull(attachFilePath)) {
                        attachType = KHUtil.isNull(attachType) ? "0" : attachType;
                        attachFileName = KHUtil.isNull(attachFileName) ? attachFilePath : attachFileName;
                        log.debug("附件路径信息:attachType:" + attachType + " attachFileName:" + attachFileName + " attachFilePath:" + attachFilePath);

                        String reAttachFilePath = attachFilePath.startsWith(H3_WoAttac_Before) ? attachFilePath.replace(H3_WoAttac_Before, H3_WoAttac_After) : attachFilePath;

                        String downPath = FileHttpUtils.downFile(reAttachFilePath, null, "UTF-8", H3_WoAttac_TempPath, attachFileName);

                        String downNGSPath = FileHttpUtils.uploadNGS(eliteBean, "/3H_WoAttac", downPath);

                        try {
                            if (downNGSPath.startsWith("3H_WoAttac/")) {
                                downNGSPath = "3H_WoAttac/" + URLEncoder.encode(downNGSPath.replace("3H_WoAttac/", ""), "UTF-8");
                            } else {
                                downNGSPath = URLEncoder.encode(downNGSPath, "UTF-8");
                            }
                        } catch (Exception e) {
                            log.warn("将上传文件下载地址做URLEncoder处理异常", e);
                        }

                        KHFileUtil.deleteFiles(downPath);

                        eliteBean.update("Insert Into Uploadlist (Uploadguid, Createdate, Path, Filename, FileDesc, Staff_Id, Guid) Values (Newid(), Getdate(), '" + downNGSPath + "', '" + attachFileName + "', '" + attachFilePath + "', 'SELITE', '" + evtId + "')", "dataSource");

                        if (!KHUtil.isNull(Rec_Id)) {

                            String ReqattachsSQL = '''Insert Into Szwg_De_Case_Reqattachs (Rec_Id, Evtid, Attachtype, Attachfilepath, Attachfilename, Attachstatus) Values (\'''' + Rec_Id + '''\', \'''' + evtId + '''\', '0', \'''' + WoAttac_CGSYS + downNGSPath + '''\', \'''' + attachFileName + '''\', 0)''';
                            eliteBean.update(ReqattachsSQL, "dataSource");
                        }

                    } else {
                        log.warn("附件路径信息异常-忽略处理:" + filearr.getJSONObject(i).toString());
                    }
                }
                reResult = true;
            } else {
                log.warn("附件List信息为空-忽略处理:" + AttachList);
            }
        } catch (Exception e) {
            log.error("附件List信息处理异常" + e.getMessage());
        }
        return reResult;

    }

    // 检查是否可以进行下一步操作
    private static String checkCaseStaus(EliteBean eliteBean, String evtId, String checkType) {
        String reResult = "";
        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 检查按键是否结案
        String checkSQL = '''Select Evtid, Status From Szwg_De_Case_List Where Evtid = ?''';

        List<Map<String, Object>> checkResultList = jt.queryForList(checkSQL, evtId);
        if (checkResultList.size() > 0) {
            String caseStatus = checkResultList.get(0).get("Status");
            if (caseStatus.equals("1")) {
                reResult = "当前案件(" + evtId + ")已结案";

            } else {
                // 申请回退 + 参数 CG_MORE_RETURN=1
                if (checkType.equals("申请回退") && KHDBConfig.getParamConfig(eliteBean, "CG_MORE_RETURN").equals("1")) {
                    checkSQL = '''Select R1.Id, R1.Activityinstid, R3.Requsername, R3.Reqdate, R3.Returndescribe, R3.Errorcode, R3.Errormsg
                                  From Szwg_De_Case_Tasks R1 With(Nolock)
                                  Left Join (Select Evtid, Max(Sync_Time) Max_Sync_Time
                                               From Szwg_De_Case_Tasks With(Nolock)
                                              Where Evtid = ?
                                              Group By Evtid) R2
                                    On R1.Evtid = R2.Evtid
                                   And R1.Sync_Time = R2.Max_Sync_Time
                                  Left Join Szwg_De_Case_Reqreturn R3 With(Nolock)
                                    On R1.Evtid = R3.Evtid
                                   And R1.Activityinstid = R3.Activityinstid
                                  Left Join (Select Evtid, Activityinstid, Max(Reqdate) As Max_Reqdate
                                               From Szwg_De_Case_Reqreturn With(Nolock)
                                              Where Evtid = ?
                                              Group By Evtid, Activityinstid) R4
                                    On R3.Evtid = R4.Evtid
                                   And R3.Activityinstid = R4.Activityinstid
                                   And R3.Reqdate = R4.Max_Reqdate
                                 Where R2.Evtid Is Not Null
                                   And R4.Evtid Is Not Null
                                   And R1.Evtid = ?''';
                    checkResultList = jt.queryForList(checkSQL, evtId, evtId, evtId);

                    // 查询有结果说明当前环节已经提交过回退
                    if (checkResultList.size() > 0) {
                        String Activityinstid = checkResultList.get(0).get("Activityinstid");
                        String Requsername = checkResultList.get(0).get("Requsername");
                        String Reqdate = checkResultList.get(0).get("Reqdate");
                        String Returndescribe = checkResultList.get(0).get("Returndescribe");
                        String Errorcode = checkResultList.get(0).get("Errorcode");
                        String Errormsg = checkResultList.get(0).get("Errormsg");

                        reResult = "案件(" + evtId + ")当前环节(" + Activityinstid + ")已经提交过回退[" + Requsername + " " + Reqdate + " #" + Returndescribe + " 同步城管结果:" + Errormsg + "(" + Errorcode + ")";

                    }
                }

                // 申请延期
                // 结果反馈 + 参数 CG_MORE_RESULT=1
                if (checkType.equals("结果反馈") && KHDBConfig.getParamConfig(eliteBean, "CG_MORE_RESULT").equals("1")) {
                    checkSQL = '''Select R1.Id, R1.Activityinstid, R3.Handlername, R3.Completetime, R3.Remark, R3.Errorcode, R3.Errormsg
                                      From Szwg_De_Case_Tasks R1
                                      Left Join (Select Evtid, Max(Sync_Time) Max_Sync_Time
                                                   From Szwg_De_Case_Tasks With(Nolock)
                                                  Where Evtid = ?
                                                  Group By Evtid) R2
                                        On R1.Evtid = R2.Evtid
                                       And R1.Sync_Time = R2.Max_Sync_Time
                                      Left Join Szwg_De_Case_Reqcomplete R3
                                        On R1.Evtid = R3.Evtid
                                       And R1.Id = R3.Taskid
                                      Left Join (Select Evtid, Taskid, Max(Completetime) As Max_Completetime
                                                   From Szwg_De_Case_Reqcomplete With(Nolock)
                                                  Where Evtid = ?
                                                  Group By Evtid, Taskid) R4
                                        On R3.Evtid = R4.Evtid
                                       And R3.Taskid = R4.Taskid
                                       And R3.Completetime = R4.Max_Completetime
                                     Where R2.Evtid Is Not Null
                                       And R4.Evtid Is Not Null
                                       And R1.Evtid = ?''';
                    checkResultList = jt.queryForList(checkSQL, evtId, evtId, evtId);

                    // 查询有结果说明当前环节已经提交过回退
                    if (checkResultList.size() > 0) {
                        String Taskid = checkResultList.get(0).get("Id");
                        String Handlername = checkResultList.get(0).get("Handlername");
                        String Completetime = checkResultList.get(0).get("Completetime");
                        String Remark = checkResultList.get(0).get("Remark");
                        String Errorcode = checkResultList.get(0).get("Errorcode");
                        String Errormsg = checkResultList.get(0).get("Errormsg");

                        reResult = "案件(" + evtId + ")当前任务(" + Taskid + ")已经提交过结果[" + Handlername + " " + Completetime + " #" + Remark + "] 同步城管结果:" + Errormsg + "(" + Errorcode + ")";

                    }
                }
            }

        } else {
            reResult = "没有对应的案件(" + evtId + ")信息";
        }

        return reResult;

    }
}
